package com.manor.im.dialog

import android.content.Context
import android.text.Editable
import android.text.TextWatcher
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter.base.listener.OnItemClickListener
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.impl.FullScreenPopupView
import com.lxj.xpopup.interfaces.OnSelectListener
import com.manor.im.R
import com.tencent.qcloud.tim.uikit.modules.group.member.GroupMemberInfo
import com.tencent.qcloud.tim.uikit.modules.group.member.GroupMemberManagerAdapter
import kotlinx.android.synthetic.main.dialog_member_search.view.*

/**
 * 搜索群聊成员
 * @date  2020/7/30  10:52
 * @version 1.0
 */
class MemberSearchDialog(context: Context, private val data: List<GroupMemberInfo>, private val listener: OnSelectListener)
    : FullScreenPopupView(context) {

    private var mAdapter: GroupMemberManagerAdapter? = null


    companion object {
        fun load(context: Context, data: List<GroupMemberInfo>, listener: OnSelectListener) {
            XPopup.Builder(context)
                    .asCustom(MemberSearchDialog(context, data, listener))
                    .show()
        }
    }


    override fun getImplLayoutId(): Int {
        return R.layout.dialog_member_search
    }

    override fun onCreate() {
        super.onCreate()
        ivDismiss.setOnClickListener { dismiss() }

        mAdapter = GroupMemberManagerAdapter(com.tencent.qcloud.tim.uikit.R.layout.group_member_adpater_new, data)
        mRecycler.layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
        mRecycler.adapter = mAdapter

        mAdapter?.setOnItemClickListener(itemClickListener)
        etSearch.addTextChangedListener(editListener)
        tvDismiss.setOnClickListener { dismiss() }
    }

    private fun doSearch(key: String) {
        val list = data.filter { it.nameCard.contains(key) || it.nickName.contains(key) }.toMutableList()
        mAdapter?.setNewInstance(list)
        mAdapter?.notifyDataSetChanged()
    }

    private val itemClickListener = OnItemClickListener { _, _, position ->
        listener.onSelect(position,"")
        dismiss()
    }

    private val editListener = object : TextWatcher {
        override fun afterTextChanged(s: Editable?) {
            s?.run {
                doSearch(this.toString())
            }
        }

        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

        }

        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

        }

    }


}